//
//  AddWishViewController.m
//  Memo
//
//  Created by A-01 on 2020/7/8.
//  Copyright © 2020 A-01. All rights reserved.
//

#import "AddWishViewController.h"
#import "DetailTableViewCell.h"
#import "TextViewTableViewCell.h"
#import "AddWishNameViewController.h"
#import "PGDatePickManager.h"
#import "ChooseStateViewController.h"

@interface AddWishViewController ()<UITableViewDelegate,UITableViewDataSource,PGDatePickerDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UIButton * saveButton;
@property (nonatomic, weak)UIButton * rightButton;
@property (nonatomic, copy)NSString * type;
@property (nonatomic, copy)NSString * name;
@property (nonatomic, copy)NSString * start;
@property (nonatomic, copy)NSString * end;
@property (nonatomic, copy)NSString * state;


@end

@implementation AddWishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.titleLabel.text = self.titleStr;
    
    [self setupUI];
}

- (void)setupUI{
    
    UIButton * rightButton = [UIButton new];
    
    [rightButton setTitle:@"Edit" forState:UIControlStateNormal];
    [rightButton setTitle:@"Done" forState:UIControlStateSelected];
    [rightButton setTitleColor:[UIColor colorWithHexString:@"F39800"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(clickRightButton) forControlEvents:UIControlEventTouchUpInside];
    rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    
    self.rightButton = rightButton;
    
    [self.view addSubview:self.rightButton];
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavHeight, kScreenW, kScreenH - kNavHeight) style:UITableViewStyleGrouped];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.sectionHeaderHeight = 0;

    self.tableView = tableView;
       
    [self.tableView registerClass:[DetailTableViewCell class] forCellReuseIdentifier:@"DetailTableViewCell"];
    [self.tableView registerClass:[TextViewTableViewCell class] forCellReuseIdentifier:@"TextViewTableViewCell"];
       
    [self.view addSubview:self.tableView];
    
    
    UIButton * saveButton = [UIButton new];
    
    [saveButton setTitle:@"Save" forState:UIControlStateNormal];
    [saveButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [saveButton setBackgroundColor:[UIColor colorWithHexString:@"F39800"]];
    [saveButton addTarget:self action:@selector(clickSaveButton) forControlEvents:UIControlEventTouchUpInside];
    saveButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    saveButton.layer.cornerRadius = 24;
    saveButton.layer.masksToBounds = YES;
    
    self.saveButton = saveButton;
    
    [self.view addSubview:self.saveButton];
    
    if ([self.titleStr isEqualToString:@"detail"]) {
        
        self.rightButton.hidden = NO;
        self.saveButton.hidden = YES;
        self.tableView.userInteractionEnabled = NO;
    }else{
        
        self.rightButton.hidden = YES;
        self.saveButton.hidden = NO;
        self.tableView.userInteractionEnabled = YES;
    }
}


- (void)clickRightButton{
    
    if (self.rightButton.selected) {
        //done
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                  message:@"Are you sure you want to update the wish?"
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                   
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault
                                                                         handler:^(UIAlertAction * action) {
                                                                        
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
            TextViewTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            
            if (![cell.textView.text isEqualToString:@"Please enter your wish details"]) {
                
                [self.dict setValue:cell.textView.text forKey:@"detail"];
            }
            
            NSArray * data = DEF_GET_OBJECT(@"data");
            NSMutableArray * arr = [NSMutableArray arrayWithArray:data];
            [arr setObject:self.dict atIndexedSubscript:self.index];
            DEF_SET_OBJECT(arr.copy, @"data");
                                                                             
            [self.navigationController popViewControllerAnimated:YES];
        }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel
        handler:^(UIAlertAction * action) {
            
        }];
                   
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        //edit
        self.rightButton.selected = YES;
        self.saveButton.hidden = NO;
        [self.saveButton setTitle:@"Delete" forState:UIControlStateNormal];
        self.tableView.userInteractionEnabled = YES;
    }
}


- (void)clickSaveButton{
    
    if ([self.saveButton.titleLabel.text isEqualToString:@"Delete"]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                  message:@"Are you sure remove the wish?"
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                   
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault
                                                                         handler:^(UIAlertAction * action) {
                                                                             
            NSArray * data = DEF_GET_OBJECT(@"data");
            NSMutableArray * arr = [NSMutableArray arrayWithArray:data];
            [arr removeObjectAtIndex:self.index];
            DEF_SET_OBJECT(arr.copy, @"data");
                                                                             
            [self.navigationController popViewControllerAnimated:YES];
        }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel
        handler:^(UIAlertAction * action) {
            
            
        }];
                   
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else{
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        
        if (!self.name) {
            
            [self showAlertViewWithTitle:@"Wish title"];
            
            return;
        }
        
        if (!self.state) {
            
            [self showAlertViewWithTitle:@"Wish state"];
            
            return;
        }
        
        if (!self.start) {
            
            [self showAlertViewWithTitle:@"Wish start time"];
            
            return;
        }
        
        if (!self.end) {
            
            [self showAlertViewWithTitle:@"Wish end time"];
            
            return;
        }
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
        TextViewTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        if ([cell.textView.text isEqualToString:@"Please enter your wish details"]) {
            
            [self showAlertViewWithTitle:@"Wish's details"];
            
            return;
        }
        
        [dict setValue:self.name forKey:@"name"];
        [dict setValue:self.state forKey:@"state"];
        [dict setValue:self.start forKey:@"start"];
        [dict setValue:self.end forKey:@"end"];
        [dict setValue:cell.textView.text forKey:@"detail"];
        
        NSArray * data = DEF_GET_OBJECT(@"data");
        NSMutableArray * arr = [NSMutableArray arrayWithArray:data];
        [arr addObject:dict];
        DEF_SET_OBJECT(arr.copy, @"data");
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        AddWishNameViewController * addNameVC = [AddWishNameViewController new];
        addNameVC.returnName = ^(NSString * _Nonnull name) {
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            DetailTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.titleLabel.text = @"Wish";
            cell.vauleLabel.text = name;
            cell.rightImageView.hidden = NO;
            
            if (self.dict) {
               
                [self.dict setValue:name forKey:@"name"];
            }else{
                
                self.name = name;
            }
        };
        [self.navigationController pushViewController:addNameVC animated:YES];
    }else if (indexPath.section == 1){
        
        if (indexPath.row == 0) {
            
            ChooseStateViewController * chooseVC = [ChooseStateViewController new];
            chooseVC.returnState = ^(NSString * _Nonnull state) {
              
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
                DetailTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                cell.titleLabel.text = @"State";
                cell.vauleLabel.text = state;
                cell.rightImageView.hidden = NO;
                
                if (self.dict) {
                   
                    [self.dict setValue:state forKey:@"state"];
                }else{
                    
                    self.state = state;
                }
            };
            
            [self.navigationController pushViewController:chooseVC animated:YES];
        }else if (indexPath.row == 2){
            
            self.type = @"start";
            [self presentDateController];
        }else if (indexPath.row == 3){
            
            self.type = @"end";
            [self presentDateController];
        }
        
    }
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 1;
    }else if (section == 1){
        
        return 4;
    }else{
        
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        
        TextViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TextViewTableViewCell" forIndexPath:indexPath];
        cell.textView.text = self.dict[@"detail"] ? self.dict[@"detail"] : @"Please enter your wish details";
        return cell;
    }else{
        
        DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailTableViewCell" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
            
            cell.titleLabel.text = @"Wish";
            cell.vauleLabel.text = self.dict[@"name"] ? self.dict[@"name"] : @"Please Enter";
            cell.rightImageView.hidden = NO;
        }else{
            
            switch (indexPath.row) {
                case 0:
                    cell.titleLabel.text = @"State";
                    cell.vauleLabel.text = self.dict[@"state"] ? self.dict[@"state"] : @"Please Enter";
                    cell.rightImageView.hidden = NO;
                    break;
                case 1:
                    cell.titleLabel.text = @"Time";
                    cell.vauleLabel.text = @"limited";
                    cell.rightImageView.hidden = YES;
                    break;
                case 2:
                    cell.titleLabel.text = @"Wish start time";
                    cell.vauleLabel.text = self.dict[@"start"] ? self.dict[@"start"] : @"";
                    cell.rightImageView.hidden = NO;
                    break;
                case 3:
                    cell.titleLabel.text = @"Wish end time";
                    cell.vauleLabel.text = self.dict[@"end"] ? self.dict[@"end"] : @"";
                    cell.rightImageView.hidden = NO;
                    break;
                    
                default:
                    break;
            }
        }
        
        return cell;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {

        return 200;
    }else if (indexPath.section == 0){
        
        return 45;
    }else{
        
        return 35;
    }
}


//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//
//
//    if (section == 0) {
//        return 0;
//    }
//    return 5;
//}


- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor clearColor];
}


- (void)presentDateController{
    
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.isShadeBackgroud = true;
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.datePickerType = PGDatePickerType1;
    datePicker.isHiddenMiddleText = false;
    datePicker.datePickerMode = PGDatePickerModeDate;
    datePicker.language = @"en";
    
    [self presentViewController:datePickManager animated:false completion:nil];
}


#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    
    NSString * date = [NSString stringWithFormat:@"%li-%02li-%02li",(long)dateComponents.year,(long)dateComponents.month,(long)dateComponents.day];
    NSIndexPath *indexPath = nil;
    if ([self.type isEqualToString:@"start"]) {
        
        indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
        DetailTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.titleLabel.text = @"Wish end time";
        cell.vauleLabel.text = date;
        cell.rightImageView.hidden = NO;
        
        if (self.dict) {
           
            [self.dict setValue:date forKey:@"start"];
        }else{
            
            self.start = date;
        }
    }else{
        
        indexPath = [NSIndexPath indexPathForRow:3 inSection:1];
        DetailTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.titleLabel.text = @"Wish end time";
        cell.vauleLabel.text = date;
        cell.rightImageView.hidden = NO;
        
        if (self.dict) {
           
            [self.dict setValue:date forKey:@"end"];
        }else{
            
            self.end = date;
        }
    }
}


//- (NSInteger)compareDate:(NSString*)aDate withDate:(NSString*)bDate
//{
//    NSInteger aa;
//    NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
//    [dateformater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate *dta = [[NSDate alloc] init];
//    NSDate *dtb = [[NSDate alloc] init];
//
//    dta = [dateformater dateFromString:aDate];
//    dtb = [dateformater dateFromString:bDate];
//    NSComparisonResult result = [dta compare:dtb];
//    if ((result=NSOrderedAscending))
//    {
//        //bDate比aDate大
//        aa=1;
//    }else {
//        //bDate比aDate小
//        aa=-1;
//
//    }
//
//    return aa;
//}

- (void)showAlertViewWithTitle:(NSString *)title{
    
    NSString * showStr = [NSString stringWithFormat:@"Please,add %@ first",title];
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                              message:showStr
                                                                       preferredStyle:UIAlertControllerStyleAlert];
               
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                     handler:^(UIAlertAction * action) {
                                                                         
                                                                         
                                                                     }];
               
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    
    [self.saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-kBarHeight - 60);
        make.height.mas_equalTo(48);
        make.width.mas_equalTo(120);
    }];
    
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.titleLabel);
        make.trailing.mas_equalTo(self.view).offset(-20);
    }];
}

@end
